package blog.service.impl;

import blog.dao.pojo.SysUser;
import blog.service.SysUserService;
import blog.utils.JwtUtils;
import blog.vo.ErrorCode;
import blog.vo.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements blog.service.LoginService {

    private static final String salt = "vs3dv$$#%";

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    // 登录
    public Result login(String account, String pwd) throws JsonProcessingException {

        // 账号密码是否为空
        if (account == null || pwd == null) {
            return Result.fail(10001, "用户名或密码不能为空！");
        }

        // 有没有想登陆的这个用户
        String password = DigestUtils.md5Hex(pwd + salt); // 对用户传进来的密码加密，以便与加密的密码比较

        SysUser sysUser = sysUserService.finUser(account, password);

        if (sysUser == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }

        // 层层验证有该用户，生成token
        String token = JwtUtils.createToken(sysUser.getId());

        ObjectMapper objectMapper = new ObjectMapper();

        // 将token和用户信息放入redis中，用户信息只有 “用户账号、头像、昵称”
        redisTemplate.opsForValue().set("TOKEN_"+token,objectMapper.writeValueAsString(sysUser),1, TimeUnit.DAYS);

        return Result.success(token);
    }

    // 退出
    @Override
    public Result logout(String token) {

        redisTemplate.delete("TOKEN_"+token);

        return Result.success("退出系统成功！");
    }

}
